/*
* @Author: Administrator
* @Date:   2018-01-13 11:29:24
* @Last Modified by:   Administrator
* @Last Modified time: 2018-01-27 12:36:17
*/
import { observable, action, toJS } from 'mobx'
import { topicList } from '../constant/api'
import { get } from '../util/request'
import objToStrMap from '../util/toMap'

class TopicListStore {
  constructor(topicsList) {
    this.topics = objToStrMap(topicsList.topics) || new Map()
  }
  @observable topics
  @observable hasMore = true
  @action getTopicList(tab, page = 1, limit) {
    const param = {
      tab,
      page,
      limit,
    }
    return new Promise((resolve, reject) => {
      const key = `${decodeURIComponent(tab)}${page}`
      if (this.topics.get(key)) {
        resolve()
        return
      }
      get(topicList, param).then((res) => {
        if (res.status === 200 && res.data.success) {
          this.hasMore = true
          const imgReg = /<img[^>]+src=['"]([^'"]+)['"]+/g;
          res.data.data.forEach((data) => {
            const imageArray = []
            const { content } = data
            let temp
            while ( temp = imgReg.exec(content) ) { //eslint-disable-line
              imageArray.push(temp[1]);
              if (imageArray.length >= 3) {
                break;
              }
            }
            data.thumbnail = imageArray
            delete data.content
          })
          this.topics.set(key, res.data.data)
          resolve()
        } else {
          this.hasMore = false
          reject(res.data)
        }
      }).catch(reject)
    })
  }
  toJson() {
    return {
      topics: toJS(this.topics),
      hasMore: this.hasMore,
    }
  }
}

export default TopicListStore
